package org.pac4j.core.credentials.password;

import org.mindrot.jbcrypt.BCrypt;
import org.pac4j.core.util.CommonHelper;

/**
 * A password encoder for bcrypt and using a salt.
 *
 * Add the <code>jBcrypt</code> dependency to use this class.
 *
 * @author Victor Noël
 * @since 1.9.2
 */
public class JBCryptPasswordEncoder implements PasswordEncoder {

    private String salt;

    /**
     * @param salt
     *            the salt to hash with (perhaps generated using {@link BCrypt#gensalt()})
     * @see BCrypt
     */
    public JBCryptPasswordEncoder(final String salt) {
        this.salt = salt;
    }

    /**
     * Use the default salt generated by {@link BCrypt#gensalt()}.
     */
    public JBCryptPasswordEncoder() {
        this.salt = BCrypt.gensalt();
    }

    @Override
    public String encode(final String password) {
        CommonHelper.assertNotBlank("salt", salt);

        return BCrypt.hashpw(password, salt);
    }

    @Override
    public boolean matches(final String plainPassword, final String encodedPassword) {
        CommonHelper.assertNotBlank("salt", salt);

        return BCrypt.checkpw(plainPassword, encodedPassword);
    }

    public String getSalt() {
        return salt;
    }

    /**
     * @param salt
     *            the salt to hash with (perhaps generated using {@link BCrypt#gensalt()})
     * @see BCrypt
     */
    public void setSalt(String salt) {
        this.salt = salt;
    }
}
